/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.jctools.actions;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipsejcde.core.JCDECore;
import org.eclipsejcde.core.defaults.Defaults;
import org.eclipsejcde.jctools.options.OptionsPreparer;

public class Convert implements IObjectActionDelegate, IWorkbenchWindowActionDelegate {
	private StructuredSelection currentSelection;

	@Override
	public void run(IAction action) {
		Iterator<?> iter = currentSelection.iterator();
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		try {
			while (iter.hasNext()) {
				Object obj = iter.next();
				if (obj instanceof IPackageFragment) {
					
					//auto save editors
					PlatformUI.getWorkbench().saveAllEditors(false);
					
					String defaultPackageAID = Defaults.PACKAGE_AID;
					String defaultAppletAID = Defaults.APPLET_AID;
					String packageAID = null;
					Map<String, String> appletAIDs = new Hashtable<String, String>();
					// extracting package AID
					IPackageFragment packFrag = (IPackageFragment) obj;
					IStatus status = JCDECore.getPackageAID(packFrag);
					if (status.getSeverity() == IStatus.OK) {
						packageAID = status.getMessage();
					} else {
						InputDialog inDialog = new InputDialog(shell, "Package AID", "Enter package AID for \"" + packFrag.getElementName() + "\" package", defaultPackageAID, null);
						if (inDialog.open() == Window.OK) {
							packageAID = inDialog.getValue();
							status = JCDECore.setPackageAID(packFrag, packageAID);
							if (status.getSeverity() != IStatus.OK) {
								MessageDialog.openError(shell, "Error", status.getMessage());
							}
						} else {
							return;
						}
					}

					// extracting applet AIDs
					ICompilationUnit[] comUnits = packFrag.getCompilationUnits();
					for (int i = 0; i < comUnits.length; i++) {
						if (JCDECore.isJavacardApplet(comUnits[i])) {
							IType type = comUnits[i].findPrimaryType();
							status = JCDECore.getAppletAID(comUnits[i]);
							if (status.getSeverity() == IStatus.OK) {
								appletAIDs.put(type.getFullyQualifiedName(), status.getMessage());
							} else {
								InputDialog inDialog = new InputDialog(shell, "Applet AID", "Enter applet AID for \"" + type.getFullyQualifiedName() + "\" applet", defaultAppletAID, null);
								if (inDialog.open() == Window.OK) {
									appletAIDs.put(type.getFullyQualifiedName(), inDialog.getValue());
									status = JCDECore.setAppletAID(comUnits[i], inDialog.getValue());
									if (status.getSeverity() != IStatus.OK) {
										MessageDialog.openError(shell, "Error", status.getMessage());
									}
								}
								inDialog.close();
							}
						}
					}

					// generate CAP
					String[] options = OptionsPreparer.prepareConverterOptions();
					status = JCDECore.convertPackage(packFrag, options);
//					if (status.getSeverity() != Status.OK) {
//						MessageDialog.openError(shell, "Error", status.getMessage());
//					}
				} else {
					if (obj instanceof IFile) {
						IFile file = (IFile) obj;
						if (file.getName().endsWith(".jca")) {
							String outputFile = file.getLocation().toFile().getAbsolutePath();
							outputFile = outputFile.substring(0, outputFile.indexOf(".jca")) + ".cap";
							String[] options = OptionsPreparer.prepareCapgenOptions();
							IStatus status = JCDECore.generateCAP(file.getLocation().toFile().getAbsolutePath(), outputFile, options);
							if (status.getSeverity() != IStatus.OK) {
								MessageDialog.openError(shell, "Error", status.getMessage());
							}
							ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
						}
					}
				}
			}
			ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (Exception e) {
			MessageDialog.openError(shell, "Error", e.getMessage());
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof StructuredSelection) {
			currentSelection = (StructuredSelection) selection;
			Iterator<?> iter = currentSelection.iterator();
			try {
				while (iter.hasNext()) {
					Object obj = iter.next();
					if (obj instanceof IPackageFragment) {
						IPackageFragment packageFragment = (IPackageFragment) obj;
						if (!packageFragment.exists() || !packageFragment.containsJavaResources()) {
							action.setEnabled(false);
						}
					}
				}
			} catch (Exception e) {
				Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				MessageDialog.openError(shell, "Error", e.getMessage());
			}
		}
	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {

	}

	@Override
	public void dispose() {

	}

	@Override
	public void init(IWorkbenchWindow window) {

	}

}
